package com.example.demo.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.atomic.AtomicLong;

@Component
public class QpsInterceptor implements HandlerInterceptor {
    // 请求计数器  
    private final AtomicLong requestCount = new AtomicLong(0);
    // 上次重置时间戳（用来计算每秒请求数）  
    private volatile long lastResetTime = System.currentTimeMillis();
    // 当前的 QPS 值  
    private volatile double qps = 0.0;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 增加请求总数  
        requestCount.incrementAndGet();
        return true;
    }

    // 定时更新 QPS 值  
    public void calculateQps() {
        long now = System.currentTimeMillis();
        long elapsedTime = now - lastResetTime; // 距离上次计算的时间间隔 (ms)  
        if (elapsedTime >= 1000) { // 每过1秒计算一下  
            synchronized (this) {
                qps = (requestCount.getAndSet(0) * 1000.0) / elapsedTime; // QPS = 请求数 / 秒  
                lastResetTime = now; // 重置时间  
            }
        }
    }

    // 获取当前的 QPS 值  
    public Double getQps() {
        return qps;
    }
}  